"use strict";

const path = require("path");
const knex = require("../../config/config.knex.js");
const { delImg, filterImgFromStr } = require("../../extend/helper.js");
const BaseService = require("./base");
const CategoryService = require("./category");
const ArticleMapTagService = require("./article_map_tag");
const ModelService = require("./model");
const FieldService = require("./field");
const MessageService = require("./message");
const UserParentService = require("./user_parent");
const UserAccountService = require("./user_account");
const UserMobileService = require("./user_mobile");
class UserService extends BaseService {
  static model = "un_user";
  constructor(props) {
    super(props);
  
  }
  // 增
  static async create(body) {
    try {
      let res, mapTag;
      const { defaultParams, fieldParams } = body;
      await knex.transaction(async (trx) => {
        const result = await knex(UserService.model)
          .insert(defaultParams)
          .transacting(trx);
        if (result[0]) {
          // 获取最后一个文章id和栏目id
          const lastStr = `SELECT id,cid FROM ${UserService.model} ORDER BY id DESC LIMIT 1`;
          const lastId = await knex.raw(lastStr, []).transacting(trx);
          const { id, cid } = lastId[0][0];

          // 通过栏目id查找模型id
          const modIdStr = `SELECT mid from ${CategoryService.model} WHERE id=${cid} LIMIT 0,1`;
          const modId = await knex.raw(modIdStr, []).transacting(trx);

          // 通过模型查找表名
          const tableNameStr = `SELECT table_name from ${ModelService.model} WHERE id=${modId[0][0].mid} LIMIT 0,1`;
          const tableName = await knex.raw(tableNameStr, []).transacting(trx);

          // 新增模型文章
          if (tableName[0].length > 0) {
            const fields = { ...fieldParams, aid: id };
            res = await knex(`${tableName[0][0].table_name}`)
              .insert(fields)
              .transacting(trx);
          }

          // 新增文章和标签关联
          const tags = defaultParams.tag_id
            .split(",")
            .map((item) => Number(item));
          const tagsql = [];
          tags.forEach((item) => {
            tagsql.push(`(${id},${item})`);
          });
          if (tags) {
            mapTag = await knex
              .raw(
                `INSERT INTO ${ArticleMapTagService.model}(aid,tid) VALUES ` +
                  tagsql.join(","),
                []
              )
              .transacting(trx);
          }

          return result[0] ? "success" : "fail";
        }
      });
    } catch (err) {
      console.error(err);
    }
  }

  // 删
  static async delete(id) {
    try {
      const ids = id.split(",");
      let arr = [];
      await knex.transaction(async (trx) => {
        const delArticleStr = `DELETE FROM ${UserService.model} WHERE id IN(${id})`;
        const delArticle = await knex.raw(delArticleStr, []).transacting(trx);
        return delArticle[0].affectedRows > 0 ? "success" : "fail";
      });
    } catch (err) {
      console.error(err);
    }
  }
  static async recharge(body)
  {
    try
    {
    const { id, field } = body;
    delete body.id;
    delete body.field;
    await knex.transaction(async (trx) => {


      const modIdStr = `update  ${UserService.model} set money=money+${body.money}  WHERE id=${id}`;
      const result = await knex.raw(modIdStr);
      return result ? "success" : "fail";
    });
    }catch(err){
      console.error(err);
    }

  }
  // 改
  static async update(body) {
    try {
      const { id, field } = body;
      delete body.id;
      delete body.field;
      await knex.transaction(async (trx) => {
      
       
        if(body.role=="1")
        {
       
          if(body.inviteCode!=null)
          {
          const modIdStr = `SELECT COUNT(id) as count from ${UserService.model} WHERE id!=${id} and inviteCode=${body.inviteCode} `;
          const total = await knex.raw(modIdStr);
         
          if(total[0][0].count>0)
          {
            return "邀请码重复";
          }
          }else{
         
            return "请输入邀请码";
          }
        }
        const result = await knex(UserService.model)
          .where("id", "=", id)
          .update(body)
          .transacting(trx);
        return result ? "success" : "fail";
      });
    } catch (err) {
      console.error(err);
    }
  }

  // 文章列表
  static async list(cur = 1, pageSize = 10) {
    try {
      // 查询个数
      let sql;
     
      sql = `SELECT COUNT(id) as count FROM ${UserService.model}`;
      
      const total = await knex.raw(sql);
      const offset = parseInt((cur - 1) * pageSize);
      let list;
    
        list = await knex
          .select([
            "id",
            "avater",
            "status",
            "money",
            "loginAddress",
            "role",
            "sex",
            "isdel",
            "remarks",
            "nickName",
            "registerTime",
            "inviteCode"
          ])
          .from(UserService.model)
          .limit(pageSize)
          .offset(offset)
          .orderBy("id", "desc");


      return {
        count: total[0].count,
        total: Math.ceil(total[0].count / pageSize),
        current: +cur,
        list: list,
      };
    } catch (err) {
      console.error(err);
    }
  }

  // 查
  static async detail(id) {
    try {
      // 查询文章
      const data = await knex(UserService.model).where("Id", "=", id).select();
      //兼容mysql错误
      // if (!data[0] || !data[0].cid) {
      //   return false;
      // }
      // 通过栏目id查找模型id
      // const modId = await knex.raw(
      //   `SELECT mid from ${CategoryService.model} WHERE userId=? LIMIT 0,1`,
      //   [data[0].cid]
      // );

      // let field = [];
      // if (modId[0].length > 0 && modId[0][0].mid !== "0") {
      //   // 通过模型查找表名
      //   const tableName = await knex.raw(
      //     `SELECT table_name from ${ModelService.model} WHERE id=?`,
      //     [modId[0][0].mid]
      //   );
      //   // 通过表名查找文章
      //   field = await knex.raw(`SELECT * FROM ? WHERE aid=? LIMIT 0,1`, [
      //     tableName[0][0].table_name,
      //     id,
      //   ]);
      // }
      return { ...data[0] };
    } catch (err) {
      console.error(err);
    }
  }

  // 搜索
  static async search(data) {
    try {
      const { cur = 1,id = "",nickName = "" ,status = "",role = "",parentId="",pageSize = 10} = data;
      // 查询个数
      console.error("-----"+parentId+"----")
      let sql;
      let fromSql = ` FROM ${UserService.model} a  LEFT JOIN ${UserMobileService.model} b ON a.Id=b.userId LEFT JOIN ${UserAccountService.model} d ON a.Id=d.userId `;
      const countSql = `SELECT COUNT(*) as count ${fromSql}`;
      let keyStr = ` where 1=1 `;
      let keyArr = [];
      sql=countSql;
      if (id != "") {
        keyStr += ` and d.account = ? `;
        keyArr.push(id);
        sql=countSql+keyStr
      }
      if (role != "") {
        keyStr += ` and a.role = ? `;
        keyArr.push(role);
        sql=countSql+keyStr
      }
      if (nickName != "") {
        keyStr += ` and a.nickName = ? `;
        sql=countSql+keyStr
        keyArr.push(nickName);
      }
      if (status != "") {
        keyStr += ` and a.status = ? `;
        sql=countSql+keyStr
        keyArr.push(status);
      }
    
      if (parentId != "") {
        keyStr += ` and a.parentId = ? `;
        sql=countSql+keyStr
        keyArr.push(parentId);
      }
     
      const total = await knex.raw(sql,keyArr);
      // 翻页
      const offset = parseInt((cur - 1) * pageSize);
      const listStart = `SELECT a.*,d.account,b.mobile mobile  ${fromSql} ${keyStr} ORDER BY a.loginTime desc LIMIT ${offset},${parseInt(
        pageSize
      )}`;
      const list = await knex.raw(listStart,keyArr);
      return {
        count: total[0][0].count,
        total: Math.ceil(total[0][0].count / pageSize),
        current: +cur,
        list: list[0],
      };
    } catch (err) {
      console.error(err);
    }
  }

  // 增加计数器
  static async count(id) {
    try {
      const result = await knex.raw(
        `UPDATE ${UserService.model} SET pv=pv+1 WHERE id=? LIMIT 1`,
        [id]
      );
      return result[0].affectedRows ? "success" : "fail";
    } catch (error) {
      console.error(error);
    }
  }

  // 上一篇文章
  static async pre(id, cid) {
    try {
      const result = await knex.raw(
        `SELECT a.id,a.title,c.name,c.path from ${UserService.model} a LEFT JOIN ${CategoryService.model} c ON a.cid=c.id  WHERE a.id<? AND a.cid=? ORDER BY id DESC LIMIT 1`,
        [id, cid]
      );
      return result[0][0];
    } catch (error) {
      console.error(error);
    }
  }

  // 下一篇文章
  static async next(id, cid) {
    try {
      const result = await knex.raw(
        `SELECT a.id,a.title,c.name,c.path from ${UserService.model} a LEFT JOIN ${CategoryService.model} c ON a.cid=c.id WHERE a.id>? AND a.cid=? LIMIT 1`,
        [id, cid]
      );
      return result[0][0];
    } catch (error) {
      console.error(error);
    }
  }

  // 通过栏目id获取mid，通过mid获取模型对应字段
  static async findField(cid) {
    try {
      // 查询个数
      const mid = `SELECT mid from ${CategoryService.model} WHERE id=${cid} AND mid IS NOT NULL`;
      const _mid = await knex.raw(mid);
      let res = [];
      if (_mid[0].length > 0) {
        const field = `SELECT field_cname,field_ename,field_type,field_values,field_default,field_sort from ${FieldService.model} WHERE model_id=${_mid[0][0].mid} LIMIT 0,12`;
        res = await knex.raw(field);
      }
      return {
        fields: res[0],
      };
    } catch (err) {
      console.error(err);
    }
  }

  static async tongji() {
    const { app } = this;
    try {
      // 昨天
      const yesterdayStr =
        `select count(*) AS count from ${UserService.model} where TO_DAYS(NOW())-TO_DAYS(updatedAt)<=1`;
      const yesterday = await knex.raw(yesterdayStr);

      // 今天
      const todayStr =
        `select count(*) AS count from ${UserService.model} where TO_DAYS(NOW())=TO_DAYS(NOW())`;
      const today = await knex.raw(todayStr);

      // 7天
      const weekStr =
        `SELECT COUNT(*) AS count from ${UserService.model} where DATE_SUB(CURDATE(),INTERVAL 7 DAY)<=DATE(updatedAt)`;
      const week = await knex.raw(weekStr);

      // 30天
      const monthStr =
        `SELECT COUNT(*) AS count from ${UserService.model} where DATE_SUB(CURDATE(),INTERVAL 30 DAY)<=DATE(updatedAt)`;
      const month = await knex.raw(monthStr);

      // 季度
      const quarterStr =
        `SELECT COUNT(*) AS count from ${UserService.model} where QUARTER(createdAt)=QUARTER(NOW())`;
      const quarter = await knex.raw(quarterStr);

      // 年
      const yearStr =
        `SELECT COUNT(*) AS count from ${UserService.model} where YEAR(createdAt)=YEAR(NOW())`;
      const year = await knex.raw(yearStr);

      // 留言数
      const messageStr = `SELECT COUNT(id) AS count from ${MessageService.model} LIMIT 0,1`;
      const message = await knex.raw(messageStr);

      return {
        yesterday: yesterday[0][0].count,
        today: today[0][0].count,
        week: week[0][0].count,
        month: month[0][0].count,
        quarter: quarter[0][0].count,
        year: year[0][0].count,
        message: message[0][0].count,
      };
    } catch (err) {
      console.error(err);
    }
  }
}

module.exports = UserService;